<template>
  <div class="full grey-bg"  @click="playSound">
    <!-- <div class="weui-panel info-top">
      <div class="weui-grids">
        <a class="weui-grid">
          <div class="mt-22">
            <div class="info-top-grid">
                <img src="img/diamonds.png" class="img-icon" alt="">
                <span>{{ user.gameAmount }}</span>
              </div>
              <p class="weui-grid__label mt-15">
                现有钻石
              </p>
          </div>
        </a>

        <a class="weui-grid no-padding-bottom">
          <div class="user-img">
            <img :src="myGroupInfo.headUrl" alt="">
          </div>
          <p class="weui-grid__label no-margin-top">
            {{ myGroupInfo.nickname }}
          </p>
          <p class="weui-grid__label no-margin-top">
            {{ user.role | agentLevel }}
          </p>
        </a>

        <a class="weui-grid" @click="gameRecord">
          <div class="mt-22">
            <div class="info-top-grid">
                <img src="img/playerGroup/flag.png" class="img-icon" alt="">
              </div>
              <p class="weui-grid__label mt-15">
                群战绩
              </p>
          </div>
        </a>
      </div>
    </div> -->

    <div class="group-item">
      <div class="group-label info-top weui-flex text-white">
        <div class="weui-flex__item" @click="toggleEdit">
          <img v-show="myGroupInfo.crowdHead" class="label-img" :src="myGroupInfo.crowdHead" alt="请上传俱乐部头像">
          <img v-show="!myGroupInfo.crowdHead" class="label-img" src="img/playerGroup/group-default-head.jpg" alt="请上传俱乐部头像">
        </div>
        <div class="weui-flex__item_3 info mt-5" @click="toggleEdit">
          <div>
            <span class="pull-left">俱乐部名: </span>{{myGroupInfo.crowdName}}
          </div>
          <div>
            <span class="pull-left">俱乐部公告: </span>{{myGroupInfo.notice}}
          </div>
        </div>
        <router-link tag="div" :to="{name: 'groupGameRecord'}" class="weui-flex__item">
          <div class="info-top-grid mt-8">
            <img src="img/playerGroup/flag.png" class="img-icon" alt="">
          </div>
          <p class="weui-grid__label" style="margin: 0;">
            战绩
          </p>
        </router-link>
        <!-- <div class="weui-flex__item arrow-block" @click="toggleActive">
          <img v-show="!active" class="arrow-down" src="img/playerGroup/down.png" alt="">
          <img v-show="active" class="arrow-up" src="img/playerGroup/up.png" alt="">  
        </div>     -->
      </div>
      <div class="text-center" @click="toggleEdit">
        <img v-show="!showEdit" class="arrows" src='img/icons/more_unfold.png'/>
        <img v-show="showEdit" class="arrows" src='img/icons/less.png'/>
      </div>
      <div v-show="showEdit" class="group-info" :style="listStyle">
        <div class="weui-cells__title">俱乐部名称</div>
        <div class="weui-cells">
          <div class="weui-cell">
            <div class="weui-cell__bd">
              <input class="weui-input" v-model.trim="modCrowdName" type="text" placeholder="俱乐部名称">
            </div>
          </div>
        </div>
        <div class="weui-cells__title">公告</div>
        <div class="weui-cells">
          <div class="weui-cell">
            <div class="weui-cell__bd">
              <input class="weui-input" v-model.trim="modNotice" type="text" placeholder="公告">
            </div>
          </div>
        </div>
        <div v-show="false" class="weui-cells__title">微信群二维码</div>
        <div v-show="false" class="weui-cells">
          <div class="weui-cell text-center" v-if="modCrowdQr">
            <img :src="modCrowdQr" alt="" class="crowd-qr">
          </div>
          <div class="weui-cell">
            <div class="weui-uploader__input-box" style="margin: auto;">
              <input @change="qrChange" ref="imageIptQr" id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="">
            </div>
          </div>
        </div>
        <div class="weui-cells__title">微信群头像</div>
        <div class="weui-cells">
          <div class="weui-cell text-center" v-if="modCrowdHead">
            <img :src="modCrowdHead" alt="" class="crowd-head">
          </div>
          <div class="weui-cell">
            <div class="weui-uploader__input-box" style="margin: auto;">
              <input @change="headChange" ref="imageIptHead" id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="">
            </div>
          </div>
        </div>
        <div class="weui-cells">
          <div class="weui-cell weui-flex">
            <div class="weui-flex__item" style="padding: 0 10px;">
              <a @click="saveGroupInfo" class="weui-btn weui-btn_primary">保存</a>  
            </div>
            <div class="weui-flex__item" style="padding: 0 10px;">
              <a @click="cancelMod" class="weui-btn weui-btn_default">取消</a>
            </div>
          </div>
          <!-- <div class="weui-cell" @click="deleteGroup">
            <a class="weui-btn weui-btn_warn" style="width: 80%;">删除玩家群</a>
          </div> -->
        </div>
        
      </div>
      <ul :style="listStyle" v-show="!showEdit" class="group-list active">
        <li class="weui-flex text-left" v-for="rule in ruleList" :key="rule.createTime" @click="memberList(rule)">
          <div class="weui-flex__item">
            <img class="label-img" :src="rule._appendInfo ? rule._appendInfo.headUrl : ''" alt="">
          </div>
          <div class="weui-flex__item_3 info">
            <p class="text-orange">
              <span>{{rule.confName}} (玩法ID: {{rule.id}})</span>
            </p>
            <p class="text-light-blue small-text">
              <span v-text="rule._appendInfo ? rule._appendInfo.ruleName : ''"></span>
            </p>
          </div>
          <!-- <div class="weui-flex__item text-white"> 
            <span>等待中房间: {{rule.waiting}}</span>
          </div> -->
        </li>
      </ul>
    </div>

    <div class="group-bottom" v-show="!showEdit">
      <div class="weui-cell weui-flex">
        <div class="weui-flex__item" style="padding: 0 10px;">
          <a class="weui-btn weui-btn_blue" @click="addRule">添加玩法</a>
        </div>
        <div class="weui-flex__item" style="padding: 0 10px;">
          <a class="weui-btn weui-btn_primary" @click="browseApply">查看申请</a>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'Vuex'
export default {
  data() {
    return {
      active: true,
      showEdit: false,
      modCrowdName: '',
      modNotice: '',
      modCrowdHead: '',
      modCrowdQr: '',
      contentHeight: 0,
      loadHeadSuc: false,
      loadQrSuc: false,
      headBlob: undefined,
      qrBlob: undefined
    }
  },
  mounted() {
    this.queryGroupInfo()
    this.contentHeight = document.body.offsetHeight - 136 - 40
    if (!this.user.role) {
      this.api.homePage.getTeamAndPlayers().then(res => res.json()).then(data => {
        if (data.errorCode) {
          return
        }
        this.changeUser({user: data.source.user})
      })
    }
  },
  methods: {
    ...mapMutations(['setMyGroupInfo', 'changeUser']),
    ...mapActions(['queryGroupInfo']),
    playSound() {
      window.btn_sound.play();
    },
    qrChange() {
      this.loadQr().then(result => {
        this.modCrowdQr = result
      })
    },
    headChange() {
      this.loadHead().then(result => {
        this.modCrowdHead = result
      })
    },
    toggleActive() {
      if (this.showEdit) {
        this.showEdit = false
        this.active = true
        return
      }
      this.active = !this.active
    },
    gameRecord() {
      this.$router.push({name: 'groupGameRecord', query: {types: 1}})
    },
    memberList(rule) {
      console.log(rule);
      this.$router.push({name: 'memberList', query: {id: rule.id}})
    },
    addRule() {
      this.$router.push({name: 'addRule'})
    },
    toggleEdit() {
      this.showEdit = !this.showEdit
      if (this.showEdit) {
        this.modCrowdName = this.myGroupInfo.crowdName
        this.modNotice = this.myGroupInfo.notice
        this.modCrowdHead = this.myGroupInfo.crowdHead
        this.modCrowdQr = this.myGroupInfo.crowdQr
      }
    },
    saveGroupInfo() {
      if (this.$refs.imageIptHead.files.length === 0) {
        const send = {
          crowdName: this.modCrowdName,
          notice: this.modNotice,
          id: this.myGroupInfo.id,
          crowdHead: this.myGroupInfo.crowdHead,
          // crowdQr: result
        }
        this.api.group.modGroupInfo(send).then(res => res.json()).then(data => {
          console.log(data);
          this.showEdit = false
          this.myGroupInfo.crowdName = this.modCrowdName
          this.myGroupInfo.notice = this.modNotice
          $.alert(data.message)
          this.queryGroupInfo()
        })
        return 
      }
      const file = this.$refs.imageIptHead.files[0]
      if (file.size >= 2032420) {
        $.alert('图片太大')
        return
      }
      const url = this.api.group.getUploadPicUrl()     
      // const url = `https://lefantian.jiahuagame.com/game-lobby/media/image/fileUpload/${Cookies.get('areaCode')}`
      let formData = new FormData()
      formData.append('file', file)
      formData.append('name', file.name)
      const opt = {
        method: 'POST',
        mode: 'cors',
        body: formData,
        // body: {
        //   file: file,
        //   name: 'hahah'
        // },
        headers: {
          Authorization: Cookies.get('token'),
          // 'Content-type': null
          // 'Content-type': 'multipart/form-data;boundary=---------------------------7d33a816d302b6',
          // 'Content-Length': 1000
        }
      }
      console.log(opt);
      fetch(url, opt).then(res => {
        console.log(res)
        return res.json()
      }).then(data => {
        console.log(data);
        const send = {
          crowdName: this.modCrowdName,
          notice: this.modNotice,
          id: this.myGroupInfo.id,
          crowdHead: data.data,
          // crowdQr: result
        }
        this.api.group.modGroupInfo(send).then(res => res.json()).then(data => {
          console.log(data);
          this.showEdit = false
          this.myGroupInfo.crowdName = this.modCrowdName
          this.myGroupInfo.notice = this.modNotice
          $.alert(data.message)
          this.queryGroupInfo()
        })
      })
      // this.loadHead().then(result => {
      //   console.log(result);
      //   const send = {
      //     crowdName: this.modCrowdName,
      //     notice: this.modNotice,
      //     id: this.myGroupInfo.id,
      //     crowdHead: result,
      //     // crowdQr: result
      //   }
      //   this.api.group.modGroupInfo(send).then(res => res.json()).then(data => {
      //     console.log(data);
      //     this.showEdit = false
      //     this.myGroupInfo.crowdName = this.modCrowdName
      //     this.myGroupInfo.notice = this.modNotice
      //     $.alert(data.message)
      //     this.queryGroupInfo()
      //   })
      // })
      // Promise.all([this.loadHead(), this.loadQr()]).then(result => {
      //   console.log(result);
      //   const send = {
      //     crowdName: this.modCrowdName,
      //     notice: this.modNotice,
      //     id: this.myGroupInfo.id,
      //     crowdHead: result[0],
      //     crowdQr: result[1]
      //   }
      //   this.api.group.modGroupInfo(send).then(res => res.json()).then(data => {
      //     console.log(data);
      //     this.showEdit = false
      //     this.myGroupInfo.crowdName = this.modCrowdName
      //     this.myGroupInfo.notice = this.modNotice
      //     $.alert(data.message)
      //     this.queryGroupInfo()
      //   })
      // })
    },
    getImgData(file) {
      return new Promise((resolve, reject) => {
        // 创建读取文件的对象  
        const reader = new FileReader()
        // 创建文件读取相关的变量  
        let imgFile
        // 为文件读取成功设置事件  
        reader.onload = function(e) {
          imgFile = e.target.result
          resolve(imgFile)
          // const blobData = window.util.dataURLtoBlob(imgFile)
          // const dataUrl = window.util.blobToDataURL(blobData, function(result) {
          //   console.log(result);
          // })
        }
        // 正式读取文件  
        reader.readAsDataURL(file)
      })
    },
    loadHead() {
      if (this.$refs.imageIptHead.files.length === 0) {
        return Promise.resolve()
      }
      const file = this.$refs.imageIptHead.files[0]
      return this.getImgData(file)
    },
    loadQr() { 
      if (this.$refs.imageIptQr.files.length === 0) {
        return Promise.resolve()
      }
      // 获取文件  
      const file = this.$refs.imageIptQr.files[0]
      return this.getImgData(file)
    },
    cancelMod() {
      this.modCrowdName = ''
      this.modNotice = ''
      this.modCrowdHead = ''
      this.modCrowdQr = ''
      this.showEdit = false
    },
    deleteGroup() {
      $.prompt({
        title: '确认删除',
        text: '该操作会删除俱乐部下的所有玩法, 输入俱乐部名以删除',
        input: '俱乐部名称',
        empty: false, // 是否允许为空
        onOK: input => {
          if (input === this.myGroupInfo.crowdName) {
            this.api.group.deleteGroup(this.myGroupInfo.id).then(res => res.json()).then(data => {
              if (data.result) {
                return
              }
              $.alert('删除成功', () => {
                this.queryGroupInfo()
                this.showEdit = false
              })
            })
          }
        }
      });
    },
    browseApply() {
      this.$router.push({name: 'groupApplyList'})
    }
  },
  computed: {
    ...mapState(['api', 'token', 'areaCode', 'user', 'myGroupInfo', 'ruleList']),
    listStyle() {
      const maxHeight = this.showEdit ? this.contentHeight + 65 : this.contentHeight
      return {
        maxHeight: maxHeight + 'px',
        'overflow-y': 'auto'
      }
    }
  },
  components: {
  }
}

</script>

<style lang="less">
@group-label-height:70px;
@group-padding: 5px;
.label-img {
  height: @group-label-height - 2 * @group-padding;
  width: @group-label-height - 2 * @group-padding;
  float: left;
  border-radius: 5px;
}
.group-label {
  // height: @group-label-height;
  padding: @group-padding 10px;
  // background: linear-gradient(to bottom, #f5f5f5,#cfcfcf);
  // &>.label-img {
  //   height: @group-label-height - 2 * @group-padding;
  //   float: left;
  // }
  &>.info {
    display: flex;
    flex-direction: column;
    height: 100%;
    padding-left: 5px;
    &>p {
      flex: 1;
      margin: 0;
    }
  }
  >.arrow-block {
    line-height: 60px;
    float: right;
  }
  .arrow-down {
    width: 20px;
  }
  .arrow-up {
    width: 20px;
  }
}
.group-list {
  padding: 0;
  margin: 0;
  display: none;
  &.active {
    display: block;
  }
  &>li {
    list-style: none;
    background: #fff;
    // height: @group-label-height - 5px;
    margin-bottom: 5px;
    padding: @group-padding 10px;
    &>.label-img {
      .label-img();
      // height: @group-label-height - 5px - 2 * @group-padding;
      // float: left;
      // border-radius: 5px;
    }
    &>.info {
      display: flex;
      flex-direction: column;
      height: 100%;
      padding-left: 5px;
      &>p {
        flex: 1;
        margin: 0;
      }
    }
  }
}
.group-bottom {
  position: absolute;
  bottom: 0;
  height: 66px;
  width: 100%;
  &>a {
    width: 80%;
    margin: auto;
  }
}

.weui-btn_blue {
  background-color: #33b0ff;
}

.waiting-room {
  // position: absolute;
  // right: 5px;
  float: right;
}

.text-center {
  text-align: center;
}

.crowd-qr {
  margin: auto;
  width: 200px;
}

.crowd-head {
  margin: auto;
  width: 60px;
}

.text-left {
  text-align: left !important;
}

.arrows {
  height: 40px;
}
</style>